#include <render/framebuffer.h>
#include <render/glextensions.h>

namespace yam3d
{
namespace render
{

FrameBuffer::FrameBuffer(int width, int height)
    : core::Object(__FUNCTION__)
    , m_fbo(0)
    , m_depthBuffer(0)
    , m_width(width)
    , m_height(height)
{
    glGenFramebuffersEXT(1, &m_fbo);
    glGenRenderbuffersEXT(1, &m_depthBuffer);
    glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, m_depthBuffer);
    glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT, m_width, m_height);
}

FrameBuffer::~FrameBuffer()
{
    glDeleteFramebuffersEXT(1, &m_fbo);
    glDeleteRenderbuffersEXT(1, &m_depthBuffer);
}


void FrameBuffer::setAsRenderTarget( bool state )
{
   if(state)
   {
        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_fbo);
        glPushAttrib(GL_VIEWPORT_BIT);
        glViewport(0, 0, m_width, m_height);
   }
   else
   {
        glPopAttrib();
        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
   }
}

bool FrameBuffer::isComplete()
{
    return GL_FRAMEBUFFER_COMPLETE_EXT == glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
}

}
}


